package mornd.test3;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;


/**
 * @author: mornd
 * @dateTime: 2023/5/13 - 17:16
 * 自定义事件发布器
 */

@Slf4j
@ComponentScan
public class App {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(App.class);
        MyService bean = context.getBean(MyService.class);
        bean.doService();
        context.close();
    }

    @Component
    static class MyService {
        @Autowired
        private ApplicationEventPublisher publisher;

        public void doService() {
            log.debug("执行业务逻辑");
            publisher.publishEvent(new MyEvent("xxxx"));
            publisher.publishEvent(new MyEvent2("xxxx2"));
        }
    }

    static class MyEvent extends ApplicationEvent {
        public MyEvent(Object source) {
            super(source);
        }
    }

    static class MyEvent2 extends ApplicationEvent {
        public MyEvent2(Object source) {
            super(source);
        }
    }

    // 监听器1
    @Component
    static class MyListener implements ApplicationListener<MyEvent> {

        @Override
        public void onApplicationEvent(MyEvent event) {
            log.debug("发送短信：{}", event.getSource());
        }
    }

    // 监听器2
    @Component
    static class MyListener2 implements ApplicationListener<MyEvent2> {

        @Override
        public void onApplicationEvent(MyEvent2 event) {
            log.debug("发送短信2：{}", event.getSource());
        }
    }
}
